import fs from "fs";
import path from "path";
// import AdmZip from "adm-zip";
import StreamZip from "node-stream-zip";
import jschardet from "jschardet";
import iconv from "iconv-lite";
const sqlite3 = require('sqlite3').verbose();

async function findCSVFiles(zipFilePath, directoryPath) {
  const zip = new StreamZip({
    file: zipFilePath,
    storeEntries: true
  });

  return new Promise((resolve, reject) => {
    zip.on('ready', () => {
      const csvFiles = [];
      zip.forEach((entry) => {
        if (!entry.isDirectory && entry.name.toLowerCase().endsWith('.csv')) {
          const extractPath = path.join(directoryPath, entry.name);
          zip.extract(entry.name, extractPath, (err) => {
            if (err) {
              console.error('Error extracting file:', err);
            } else {
              csvFiles.push(extractPath);
            }
          });
        }
      });

      zip.on('extract', () => {
        zip.close();
        resolve(csvFiles);
      });

      zip.on('error', (err) => {
        zip.close();
        reject(err);
      });
    });

    zip.on('error', (err) => {
      reject(err);
    });
  });
}


function unzipAndImportToDatabase(zipFilePath, extractPath, dbFilePath, tableName) {
  const zip = new AdmZip(zipFilePath, "GBK");
  zip.extractAllTo(extractPath, true);

  const csvFiles = findCSVFiles(extractPath);
  const db = new sqlite3.Database(dbFilePath);

  let successCount = 0;

  csvFiles.forEach((filePath) => {
    const fileName = path.basename(filePath);
    // const fileNameBuffer = Buffer.from(fileName, 'binary');
    // const decodedFileName = iconv.decode(fileNameBuffer, 'GBK');
    if (fileName.includes('交易明细信息')) {
      console.log(fileName);
      const fileBuffer = fs.readFileSync(filePath);
      const detectedFileEncoding = jschardet.detect(fileBuffer);
      const decodedFileContent = iconv.decode(fileBuffer, detectedFileEncoding.encoding);
      const csvData = decodedFileContent.toString();
      const rows = csvData.split('\n').map((row) => row.split(','));
      rows.forEach((data) => {
        const sql = buildsql(tableName,data)
        db.run(sql, function (err) {
          if (!err) {
            successCount++;
          }
        });
      });
    }
  });

  db.close();
  fs.rm(extractPath, { recursive: true }, (err) => {
    if (err) {
      console.error('无法删除文件夹:', err);
    } else {
      console.log('文件夹删除成功');
    }
  })
  return `成功插入 ${successCount} 条数据到数据库。`;
}

function buildsql (table,data) {

  const [
    column1, column2, column3, column4, column5, column6, column7, column8,
    column9, column10, column11, column12, column13, column14, column15, column16,
    column17, column18, column19, column20, column21, column22, column23, column24,
    column25, column26, column27, column28, column29, column30, column31, column32
  ] = data; // 将实际的数据存储在对应的变量中

  const columns = [
    'j_y_k_h', 'j_y_z_h', 'c_x_f_k_j_g_y_y_y', 'j_y_h_m', 'j_y_z_j_h_m',
    'j_y_s_j', 'j_y_j_e', 'j_y_y_e', 's_f_b_z', 'j_y_d_s_z_h', 'x_j_b_z',
    'd_s_h_m', 'd_s_s_f_z_h', 'd_s_k_h_y_h', 'z_h_s_m', 'j_y_b_z',
    'j_y_w_d_m_c', 'j_y_f_s_d', 'j_y_s_f_c_g', 'p_h', 'IP_d_z', 'MAC_d_z',
    'd_s_j_y_y_e', 'j_y_l_s_h', 'r_z_h', 'p_z_z_l', 'p_z_h', 'j_y_g_y_h_h',
    'b_z', 's_h_m_c', 's_h_d_m', 'j_y_l_x'
  ];

  const values = [
    column1, column2, column3, column4, column5, column6, column7, column8,
    column9, column10, column11, column12, column13, column14, column15, column16,
    column17, column18, column19, column20, column21, column22, column23, column24,
    column25, column26, column27, column28, column29, column30, column31, column32
  ];

  const insertStatement = `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${values.map(value => `'${value}'`).join(', ')});`;

  return insertStatement
}

const arg1 = process.argv[1];
const arg2 = process.argv[2];
const arg3 = process.argv[3];
const arg4 = process.argv[4];
console.log(arg1)
console.log(arg2)
console.log(arg3)
console.log(arg4)
unzipAndImportToDatabase(arg1,arg2,arg3,arg4)
